package com.anlogic.sdk.app.ui;

import java.lang.reflect.InvocationTargetException;

import org.apache.logging.log4j.Logger;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;

import com.anlogic.sdk.app.handlers.NewApplicationProjectHandler;
import com.anlogic.sdk.utils.LogUtils;

public class NewApplicationProjectWizard extends Wizard implements INewWizard {
	private static Logger logger = LogUtils.getLogger(NewApplicationProjectWizard.class);
	
	private NewApplicationProjectWizardPage appProjWizardPage;
	
	public NewApplicationProjectWizard() {
		super();
		setNeedsProgressMonitor(true);
	}

	@Override
	public void addPages() {
		appProjWizardPage = new NewApplicationProjectWizardPage();
		addPage(appProjWizardPage);
	}
	
	@Override
	public void init(IWorkbench workbench, IStructuredSelection selection) {}

	@Override
	public boolean performFinish() {
		return createApplicationProject();
	}
	
	private boolean createApplicationProject() {
		IRunnableWithProgress op = monitor -> {
			try {
				createAppProject(monitor);
			} catch (CoreException e) {
				throw new InvocationTargetException(e);
			} finally {
				refreshProject(appProjWizardPage.getModel().getProjName());
				monitor.done();
			}
		};
		try {
			getContainer().run(true, false, op);
		} catch (InterruptedException e) {
			logger.error("Create Application Project Error {}", e.getMessage());
			return false;
		} catch (InvocationTargetException e) {
			logger.error("Create Application Project Failed");
			Throwable realException = e.getTargetException();
			MessageDialog.openError(getShell(), "Error", realException.getMessage());
			return false;
		}
		return true;
	}

	private void createAppProject(IProgressMonitor monitor) throws CoreException {
		NewApplicationProjectHandler.newInstance(appProjWizardPage.getModel()).run(monitor);
	}
	
	public void refreshProject(String projName) {
		try {
			IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projName);
			if (project.exists()) {
				project.refreshLocal(IResource.DEPTH_INFINITE, null);
			}
		} catch (CoreException e) {
			logger.error("Create Platform Project Error while refreshing platform project {}", e.getMessage());
		}
	}
}
